# !/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
@作者 杨阳
@时间 2018-07-19
@说明 activeMQ工具类
@注意事项
"""
# 提交考试的队列(即点对点式）
import time

import stomp

from settings import ACTIVEMQ_HOST, ACTIVEMQ_PORT

# 队列名称
queue_name = '/queue/ExamQueue'
# 多消费得队列（即订阅模式）
topic_name = '/topic/SampleTopic'
# 考试队列消费得
exam_listener_name = '/queue/ExamQueue'
# 订阅模式消费得
topic_listener_name = '/topic/SampleTopic'


class SampleListener(object):
    """
    activeMQ接收消息监听器类
    """

    def on_message(self, headers, message):
        """
        正确接收消息方法
        :param headers:     消息头
        :param message:     消息内容
        :return:
        """
        print('接收到headers: %s' % headers)
        print('接收到message: %s' % message)

    def on_error(self, headers, message):
        """
        接收消息异常方法
        :param headers:     消息头
        :param message:     消息内容
        :return:
        """
        print('接收到error headers: %s' % headers)
        print('接收到error message: %s' % message)


def send_to_queue(list):
    """
    推送到队列queue
    注意：这里有一个坑，activeMQ最大允许连接数默认是1000，如果超出了。
    需要D:\apache-activemq-5.15.4\conf\activemq.xml配置maximumConnections属性
    :param list:     消息集合，需要循环取出
    :return:
    """
    conn = stomp.Connection10([(ACTIVEMQ_HOST, ACTIVEMQ_PORT)])
    conn.start()
    conn.connect()
    for msg in list:
        conn.send(queue_name, msg)
    conn.disconnect()


# 推送到主题
def send_to_topic(msg):
    conn = stomp.Connection10([(ACTIVEMQ_HOST, ACTIVEMQ_PORT)])
    conn.start()
    conn.connect()
    conn.send(topic_name, msg)
    conn.disconnect()


def receive_from_queue():
    """
    从队列接收消息
    :return:
    """
    conn = stomp.Connection10([(ACTIVEMQ_HOST, ACTIVEMQ_PORT)])
    conn.set_listener(exam_listener_name, SampleListener())
    conn.start()
    conn.connect()
    conn.subscribe(queue_name)
    time.sleep(2)  # secs
    conn.disconnect()


def receive_from_topic():
    """
    从主题接收消息
    :return:
    """
    conn = stomp.Connection10([(ACTIVEMQ_HOST, ACTIVEMQ_PORT)])
    conn.set_listener(topic_listener_name, SampleListener())
    conn.start()
    conn.connect()
    conn.subscribe(topic_name)
    while 1:
        send_to_topic('topic')
        time.sleep(3)  # secs
    conn.disconnect()


if __name__ == '__main__':
    list = ["好唱了歌", "不好", "好的", "还是不好"]
    send_to_queue(list)
    receive_from_queue()
